
package com.wwy.monitor.controller;

import com.alibaba.buc.api.exception.BucException;
import com.alibaba.buc.sso.client.vo.BucSSOUser;
import com.wwy.monitor.common.BizResult;
import com.wwy.monitor.exception.BizEnum;
import com.wwy.monitor.exception.BizException;
import com.wwy.monitor.model.vo.AclCheckActionResult;
import com.wwy.monitor.model.vo.PermissionInfoResult;
import com.wwy.monitor.service.acl.PermissionService;
import com.wwy.monitor.service.acl.UrlCheckService;
import com.wwy.monitor.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/api/permission")
@Slf4j
public class PermissionController {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UrlCheckService urlCheckService;

    @RequestMapping(value = "check", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BizResult hasPermission(HttpServletRequest httpServletRequest, String pname) throws IOException, ServletException, BucException {
        if (pname == null) {
            throw new BizException(BizEnum.ERR_INVALID_PARAM);
        }
        BucSSOUser bucSSOUser = UserUtils.getUser(httpServletRequest);
        if (Objects.isNull(bucSSOUser)) {
            throw new BizException(BizEnum.ERR_NOT_LOGIN);
        }
        PermissionInfoResult permissionInfoResult = permissionService.check(bucSSOUser.getId().longValue(), pname);
        return BizResult.view(permissionInfoResult);
    }

    @RequestMapping(value = "url-check", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BizResult urlCheck(HttpServletRequest httpServletRequest, String path) throws IOException, ServletException, BucException {
        BucSSOUser bucSSOUser = UserUtils.getUser(httpServletRequest);
        if (Objects.isNull(bucSSOUser)) {
            throw new BizException(BizEnum.ERR_NOT_LOGIN);
        }
        AclCheckActionResult result = urlCheckService.checkActions(bucSSOUser.getId().intValue(), path);
        return BizResult.view(result);
    }
}